package com.example.gateway.filter;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import java.util.List;
/**
 * 网关转发服务的拦截器
 * 名称必须是xxxGatewayFilterFactory形式
 * 模拟授权的验证，具体逻辑根据业务完善
 * 网关转发具体服务的时候才会走该代码的逻辑，需要在配置文件配置 -Preview  为true进行拦截，不配置或false不生效
 */
@Component
@Log4j2
public class PreviewGatewayFilterFactory extends AbstractGatewayFilterFactory<PreviewGatewayFilterFactory.Config> {
    public PreviewGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Lists.newArrayList("enabled");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            log.info("每次路由匹配到会执行");
            Boolean enabled = config.getEnabled();
            log.info("从配置文件中获取到的 enabled 的值=[{}].", enabled);
            return chain.filter(exchange);
        };
    }
    @Data
    public static class Config {
        private Boolean enabled;
    }

}
